package edu.wuster.blog.exception;

/*
 * 全局异常处理器
 * */

import edu.wuster.blog.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    //数据校验异常处理
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException bindException) {
        log.info("捕获到数据校验异常");
        //数据校验返回错误信息
        StringBuilder str = new StringBuilder();
        List<ObjectError> allErrors = bindException.getAllErrors();
        for (ObjectError error : allErrors) {
            str.append(error.getDefaultMessage());
            str.append("，");
        }
        log.info(str.toString());
        return Result.error(str.toString());
    }

    //通用异常处理
    @ExceptionHandler(Exception.class)
    public Result handle(Exception exception) {
        log.info("捕获到异常：{}", exception.getMessage());
        return Result.error(exception.getMessage());
    }
}
